package com.liu.QQ.client.service;

import com.liu.QQ.Message;
import com.liu.QQ.MessageType;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

/**
 * @author liuchengjie
 */
public class ClientConnectThread extends Thread{

    private Socket socket;

    public ClientConnectThread(Socket socket) {
        this.socket = socket;
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        while (true) {
            try {
                ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
                Message message = (Message)objectInputStream.readObject();
                //判断message类型，做相应的业务处理
                //获取到在线用户
                if (message.getMesType().equals(MessageType.MESSAGE_RET_ONLINE_FRIEND)) {
                    //取出在线列表信息
                    //规定，在线用户列表内容形式：userId userId.....
                    String[] onlineUserList = message.getContent().split(" ");
                    System.out.println("\n=======用户列表========");
                    for (int i = 0; i < onlineUserList.length; i++) {
                        System.out.println("用户："+onlineUserList[i]);
                    }
                }
                //私聊消息
                if (message.getMesType().equals(MessageType.MESSAGE_COMM_MES)) {
                    String content = message.getContent();
                    System.out.println(message.getSender() + "向我发送了一条消息：");
                    System.out.println(content);
                }
                //系统发送的消息
                if (message.getMesType().equals(MessageType.MESSAGE_SERVER)) {
                    System.out.println(message.getContent());
                }
                //接收群发消息
                if (message.getMesType().equals(MessageType.MESSAGE_DISTRIBUTION)) {
                    System.out.println(message.getSender() + "向我发送了一条消息：");
                    System.out.println(message.getContent());
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}
